<template>
	<div class="system-role-container layout-padding">
		<div class="system-role-padding layout-padding-auto layout-padding-view">
			<div class="system-user-search mb15">
				<el-input v-model="state.tableData.param.couponName" size="default" placeholder="请输入优惠券名"
					style="max-width: 180px"> </el-input>
				<el-button size="default" type="primary" class="ml10" @click="querycoupon()">
					<el-icon>
						<ele-Search />
					</el-icon>
					查询
				</el-button>
				<el-button size="default" type="success" class="ml10" @click="onOpenAddRole()">
					<el-icon>
						<ele-FolderAdd />
					</el-icon>
					新增优惠券
				</el-button>
			</div>

			<el-table :data="state.tableData.data" v-loading="state.tableData.loading" style="width: 100%">
				<el-table-column prop="id" label="序号" width="60" />
				<el-table-column prop="couponName" label="优惠券名"></el-table-column>
				<el-table-column prop="quota" label="优惠券额度"></el-table-column>
				<el-table-column prop="number" label="优惠券数量"></el-table-column>
				<!-- <el-table-column prop="status" label="角色状态" >
					<template #default="scope">
						<el-tag type="success" v-if="scope.row.status">启用</el-tag>
						<el-tag type="info" v-else>禁用</el-tag>
					</template>
</el-table-column> -->
				<el-table-column prop="beginTime" label="起始时间"></el-table-column>
				<el-table-column prop="overtime" label="结束时间"></el-table-column>

				<el-table-column label="操作" width="100">
					<template #default="scope">
						<el-button size="small" text type="primary" @click="updates(scope.row)">修改</el-button>
						<el-button size="small" text type="danger" @click="deletes(scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>



			<div class="system-role-dialog-container">
				<el-dialog :title="statses.dialog.title" v-model="statses.dialog.isShowDialog" width="769px">
					<el-form ref="roleDialogFormRef" :model="statses.ruleForm" size="default" label-width="90px">
						<el-row :gutter="35">
							<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
								<el-form-item label="优惠券名称">
									<el-input v-model="statses.ruleForm.couponName" placeholder="请输入优惠券名称"
										clearable></el-input>
								</el-form-item>
							</el-col>

							<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
								<el-form-item label="优惠额度">
									<el-input v-model="statses.ruleForm.quota" type="number" placeholder="请输入优惠券名称"
										@change="validate(statses.ruleForm.quota)" clearable></el-input>
								</el-form-item>
							</el-col>

							<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
								<el-form-item label="优惠券数量">
									<el-input-number v-model="statses.ruleForm.number" :min="0" :step="1"
										placeholder="请输发放优惠券数量" @change="validateNumber(statses.ruleForm.number)"
										class="w100" />
								</el-form-item>
							</el-col>


							<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
								<el-form-item label="起始时间">
									<el-date-picker v-model="statses.ruleForm.beginTime" type="datetime"
										@change="beginTimeChange"></el-date-picker>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
								<el-form-item label="结束时间">
									<el-date-picker v-model="statses.ruleForm.overtime" type="datetime"
										@change="overtimeChange"></el-date-picker>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>
					<template #footer>
						<span class="dialog-footer">
							<el-button @click="oncancel()" size="default">取 消</el-button>
							<el-button type="primary" @click="add()" size="default">{{ statses.dialog.submitTxt
								}}</el-button>
						</span>
					</template>
				</el-dialog>
			</div>



			<div class="system-role-dialog-container">
				<el-dialog :title="statses.dialog.title" v-model="statses.dialog.load" width="769px">
					<el-form ref="roleDialogFormRef" :model="statses.ruleForm" size="default" label-width="90px">
						<el-row :gutter="35">
							<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
								<el-form-item label="优惠券名称">
									<el-input v-model="statses.ruleForm.couponName" placeholder="请输入优惠券名称"
										clearable></el-input>
								</el-form-item>
							</el-col>

							<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
								<el-form-item label="优惠额度">
									<el-input v-model="statses.ruleForm.quota" type="number" placeholder="请输入优惠券名称"
										@change="validate(statses.ruleForm.quota)" clearable></el-input>
								</el-form-item>
							</el-col>

							<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
								<el-form-item label="优惠券数量">
									<el-input-number v-model="statses.ruleForm.number" :min="0" :step="1"
										placeholder="请输发放优惠券数量" @change="validateNumber(statses.ruleForm.number)"
										class="w100" />
								</el-form-item>
							</el-col>


							<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
								<el-form-item label="起始时间">
									<el-date-picker v-model="statses.ruleForm.beginTime" type="datetime"
										@change="beginTimeChange"></el-date-picker>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
								<el-form-item label="结束时间">
									<el-date-picker v-model="statses.ruleForm.overtime" type="datetime"
										@change="overtimeChange"></el-date-picker>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>
					<template #footer>
						<span class="dialog-footer">
							<el-button @click="oncancel()" size="default">取 消</el-button>
							<el-button type="primary" @click="update()" size="default">{{ statses.dialog.updatatTxt
								}}</el-button>
						</span>
					</template>
				</el-dialog>
			</div>


			<el-pagination v-if="statses.dialog.laoding" @size-change="onHandleSizeChange"
				@current-change="onHandleCurrentChange" class="mt15" :pager-count="5" :page-sizes="[10, 20, 30]"
				v-model:current-page="state.tableData.param.pageNum" background
				v-model:page-size="state.tableData.param.pageSize" layout="total, sizes, prev, pager, next, jumper"
				:total="state.tableData.total">
			</el-pagination>
		</div>
		<!-- <RoleDialog ref="roleDialogRef" @refresh="getTableData()" /> -->
	</div>
</template>

<script setup lang="ts" name="systemRole">
import { defineAsyncComponent, reactive, onMounted, ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { useCouponApi } from '/@/api/coupon/index';


// 引入组件
const RoleDialog = defineAsyncComponent(() => import('/@/views/system/role/dialog.vue'));

// 定义变量内容
const roleDialogRef = ref();
const state = reactive<SysRoleState>({
	tableData: {
		data: [],
		total: 0,
		loading: false,
		param: {
			couponName: "",
			pageNum: 1,
			pageSize: 10,
		},
	},
});


const statses = reactive({
	ruleForm: {
		couponName: "", // 优惠券名称
		quota: 0, // 优惠额度
		number: 0, // 排序
		beginTime: "", // 起始时间
		overtime: "", // 结束时间
	},
	dialog: {
		load: false,
		laoding: true,
		isShowDialog: false,
		type: '',
		title: '新增优惠券',
		submitTxt: '新增',
		updatatTxt: '修改',
	},
});



//搜锁优惠券
const querycoupon = async () => {
	//判断couponName是否为空
	if (state.tableData.param.couponName === '') {
		statses.dialog.laoding = true
		getCoupon();
	} else {
		useCouponApi().select({ couponName: state.tableData.param.couponName, pageNum: state.tableData.param.pageNum, pageSize: state.tableData.param.pageSize }).then(res => {
			if (res.data.length <= 0) {
				getCoupon();
				ElMessage.warning('暂无数据')
			} else {

				statses.dialog.laoding = false
				state.tableData.data = res.data
			}

		})
	}
}

//获取所有优惠券的数据
 

const getCoupon = async () => {
	useCouponApi().query({ pageNum: state.tableData.param.pageNum, pageSize: state.tableData.param.pageSize }).then(res => {
		state.tableData.data = res.data.records
		state.tableData.total = res.data.total
	})

}
//新增优惠券
const add = async () => {
	useCouponApi().add(statses.ruleForm).then(res => {
		if (res.code == 0) {
			ElMessage.error(res.msg)
		} else {
			oncancel();
			getCoupon();
			ElMessage.success('新增成功')
		}

	})

}

//修改数据
const updates = (row: any) => {
	statses.dialog.load = true
	statses.ruleForm = row
	getCoupon()
}


const update = async () => {
	console.log(statses.ruleForm)
	beginTimeChange(statses.ruleForm.beginTime)
	overtimeChange(statses.ruleForm.overtime)
	useCouponApi().update(statses.ruleForm).then(res => {
		if(res.code==0){
			ElMessage.warning(res.msg)
		}else{
			ElMessage.success('修改成功')
			oncancel()
			getCoupon()
		}
	})
}

//删除优惠券
const deletes = (row: any) => {
	useCouponApi().delete({ id: row.id }).then(res => {
		ElMessage.success('删除成功')
		getCoupon()
		
	})
}


//开始时间转化
const beginTimeChange = (val: any) => {
	const date = new Date(val)
	statses.ruleForm.beginTime = time(date)
}
//结束时间转化
const overtimeChange = (val: any) => {
	const date = new Date(val)
	statses.ruleForm.overtime = time(date)
}
//时间格式化
const time = (date: any) => {
	const year = date.getFullYear();
	const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需加1  
	const day = String(date.getDate()).padStart(2, '0');
	const hours = String(date.getHours()).padStart(2, '0');
	const minutes = String(date.getMinutes()).padStart(2, '0');
	const seconds = String(date.getSeconds()).padStart(2, '0');
	return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

}

//打开新增优惠券窗口
const onOpenAddRole = () => {
	statses.dialog.isShowDialog = true
}

//关闭新增优惠券窗口
const oncancel = () => {
	statses.dialog.load = false
	statses.dialog.isShowDialog = false

	statses.ruleForm = {
		couponName: "", // 优惠券名称
		quota: 0, // 优惠额度
		number: 0, // 排序
		beginTime: "", // 起始时间
		overtime: "", // 结束时间
	}
}

//确保优惠券的数量是整数
const validateNumber = (val: number) => {
	statses.ruleForm.number = parseInt(val.toString())
}

//确保优惠额度大于零且保留两位小数
const validate = (val: number) => {
	if (val < 0) {
		ElMessage.error("输入优惠额度必须是数字且大于零，小数只保留两位小数");
		statses.ruleForm.quota = 0
	} else {
		statses.ruleForm.quota = Math.round(val * 100) / 100
	}
}

// 分页改变
const onHandleSizeChange = (val: number) => {
	state.tableData.param.pageSize = val;
	getCoupon()

};
// 分页改变
const onHandleCurrentChange = (val: number) => {
	state.tableData.param.pageNum = val;
	getCoupon()
};
// 初始化表格数据
const getTableData = () => {
	state.tableData.loading = true;
	const data = [];
	for (let i = 0; i < 20; i++) {
		data.push({
			roleName: i === 0 ? '超级管理员' : '普通用户',
			roleSign: i === 0 ? 'admin' : 'common',
			describe: `测试角色${i + 1}`,
			sort: i,
			status: true,
			createTime: new Date().toLocaleString(),
		});
	}
	state.tableData.data = data;
	state.tableData.total = state.tableData.data.length;
	setTimeout(() => {
		state.tableData.loading = false;
	}, 500);
};




// 页面加载时
onMounted(() => {
	getCoupon();
});
</script>

<style scoped lang="scss">
.system-role-container {
	.system-role-padding {
		padding: 15px;

		.el-table {
			flex: 1;
		}
	}
}
</style>
